package com.hcss.common.util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @Author: 可乐
 * @Description:
 * @CreateTime: 2023-03-17  15:29
 */
public class PostMultipartUtil {
	public static String sendPost( String urlString,List< File > files,String modelName,RedisTemplate redisTemplate ) throws UnsupportedEncodingException {
		String result = "";
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(urlString);
		MultipartEntity entity = new MultipartEntity();
		StringBody model=new StringBody( modelName );
		for(File file: files) {
				if (file.exists()) {
					entity.addPart("file", new FileBody(file));
				}
		}
		entity.addPart( "model",model );
		try {
			httpPost.setEntity(entity);
			HttpResponse response = client.execute(httpPost);
			HttpEntity responseEntity = response.getEntity();
			result = EntityUtils.toString(responseEntity);
		} catch(IOException e) {
			String[] split=modelName.split( "\\*" );
			redisTemplate.delete( split[1] );
			e.printStackTrace( );
			result=e.getMessage();
		}
		return result;
	}
}
